package com.fourpigeon.utils;

import cn.hutool.core.util.StrUtil;
import com.fourpigeon.controller.UploadController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.fourpigeon.utils.RedisConstants.*;


/**
 * 自定义"垃圾"处理器
 * 针对Redis无用数据的释放
 * 譬如无用图片、无用token
 */
@Slf4j
@Configuration
@EnableScheduling//开启定时任务
public class GarbageHandler {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UploadController uploadController;

    /**
     * 定时清除存储桶图片
     * 24h10min
     */
    @Deprecated
    @Scheduled(fixedDelay = 1450,timeUnit = TimeUnit.MINUTES)
    public void clearImg(){
        //计算差集
        Set<String> difference = stringRedisTemplate.opsForSet().difference(UPLOAD_FILE_SET, UPLOAD_FILE_CONFIRM_SET);
        if (difference!=null&&!difference.isEmpty()) {
            System.out.println("difference size: "+difference.size());
            for (String s : difference) {
//                String key = StrUtil.subAfter(s, "com/", true);
                //不是暂存状态
                if (stringRedisTemplate.opsForValue().get(UPLOAD_FILE_CONFIRM_STRING + s) == null) {
                    //删除图片
                    uploadController.delImg(s);
                    log.info("delete img: "+s);
                    //Redis移除记录
                    stringRedisTemplate.opsForSet().remove(UPLOAD_FILE_SET,s);
                }
            }
        }
    }
}
